package com.example.gymmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.gymmanagement.Utils.Result;
import com.example.gymmanagement.Utils.StatusCode;
import com.example.gymmanagement.domain.Bill;
import com.example.gymmanagement.domain.Field;
import com.example.gymmanagement.domain.Rent;
import com.example.gymmanagement.domain.User;
import com.example.gymmanagement.mapper.BillMapper;
import com.example.gymmanagement.mapper.FieldMapper;
import com.example.gymmanagement.mapper.RentMapper;
import com.example.gymmanagement.mapper.UserMapper;
import com.example.gymmanagement.service.FieldService;
import com.example.gymmanagement.service.RentService;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author 蜗牛菌
 * @description 针对表【field】的数据库操作Service实现
 * @createDate 2023-06-06 13:12:01
 */
@Service
public class FieldServiceImpl extends ServiceImpl<FieldMapper, Field> implements FieldService {

    @Autowired
    private FieldMapper fieldMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RentMapper rentMapper;
    @Autowired
    private BillMapper billMapper;
    @Autowired
    private RentService rentService;

    @Override
    public boolean insert(Field field) {
        boolean success = false;
        try {
            success = this.fieldMapper.insert(field) > 0;
        } catch (Exception e) {
            success = false;
        }
        return success;
    }

    @Override
    public boolean deleteById(Integer id) {
        return this.fieldMapper.deleteById(id) > 0;
    }

    @Override
    public boolean updateField(Field field) {
        UpdateWrapper<Field> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("field_id", field.getFieldId()); // 设置 WHERE 条件

        if (field.getFieldName() != null && field.getFieldName() != "") {
            updateWrapper.set("field_name", field.getFieldName());  // 筛选需要更新的列
        }
        if (field.getFieldNotice() != null && field.getFieldNotice() != "") {
            updateWrapper.set("field_notice", field.getFieldNotice());
        }
        if (field.getFieldTime() != null && field.getFieldTime() != "") {
            updateWrapper.set("field_time", field.getFieldTime());
        }
        if (field.getFieldPrice() != null && field.getFieldPrice() != "") {
            updateWrapper.set("field_price", field.getFieldPrice());
        }
        if (field.getFieldPriceLight() != null && field.getFieldPriceLight() != "") {
            updateWrapper.set("field_price_Light", field.getFieldPriceLight());
        }
        if (field.getFieldDetail() != null && field.getFieldDetail() != "") {
            updateWrapper.set("field_detail", field.getFieldDetail());
        }

        return this.fieldMapper.update(null, updateWrapper) > 0; // 执行修改操作
        //return this.fieldMapper.updateById(field) >0;
    }

    @Override
    public Result selectList(int index, int size, Field field) {
        if (index <= 0) {
            index = 1;
        }
        if (size <= 0) {
            size = 10;
        }
        Page<Field> pageInfo = new Page(index, size);

        LambdaQueryWrapper<Field> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (field.getFieldId() != null && field.getFieldId() != 0 && !Objects.equals(field.getFieldId(), "")) {
            lambdaQueryWrapper.eq(Field::getFieldId, field.getFieldId());
        }
        if (StringUtils.isNotEmpty(field.getFieldName()) && !Objects.equals(field.getFieldName(), "")) {
            lambdaQueryWrapper.like(Field::getFieldName, field.getFieldName());
        }
        if (StringUtils.isNotEmpty(field.getFieldNotice()) && !Objects.equals(field.getFieldNotice(), "")) {
            lambdaQueryWrapper.like(Field::getFieldNotice, field.getFieldNotice());
        }
        if (StringUtils.isNotEmpty(field.getFieldTime()) && !Objects.equals(field.getFieldTime(), "")) {
            lambdaQueryWrapper.like(Field::getFieldTime, field.getFieldTime());
        }
        if (StringUtils.isNotEmpty(field.getFieldPrice()) && !Objects.equals(field.getFieldPrice(), "")) {
            lambdaQueryWrapper.eq(Field::getFieldPrice, field.getFieldPrice());
        }
        if (StringUtils.isNotEmpty(field.getFieldPriceLight()) && !Objects.equals(field.getFieldPriceLight(), "")) {
            lambdaQueryWrapper.eq(Field::getFieldPriceLight, field.getFieldPriceLight());
        }
        if (StringUtils.isNotEmpty(field.getFieldDetail()) && !Objects.equals(field.getFieldDetail(), "")) {
            lambdaQueryWrapper.like(Field::getFieldDetail, field.getFieldDetail());
        }

        Page<Field> fieldList = fieldMapper.selectPage(pageInfo, lambdaQueryWrapper);

        System.out.println("total:" + fieldList.getTotal());
        Integer code = fieldList.getTotal() != 0 ? StatusCode.GET_OK : StatusCode.GET_ERR;
        String msg = fieldList.getTotal() != 0 ? "查询成功,数据量为：" + fieldList.getTotal() : "未查询到数据";
        return new Result(code, fieldList, msg);
    }

    @Override
    public Result booking(Long id, Long userNum, LocalDateTime fieldBookingTime, int timeSize, int light) {
        boolean flag = true;
        String msg = "预约场地成功";
        QueryWrapper<Rent> queryWrapper = new QueryWrapper<>();
        if (userMapper.selectById(userNum).getUserCred() >= 60) {
            //信用不低于60
            queryWrapper.eq("rent_field", id);
            List<Rent> rentList = rentService.list(queryWrapper);
            for (Rent rent : rentList) {
                if (rent.getRentStatus().equals("预约中")) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                //场地没有被租用
                System.out.println("rentList 是空的,场地没有被租用");
                //msg ="rentList 是空的,场地没有被租用";

                double ff = 0;
                Field field = fieldMapper.selectById(id);
                String fieldPrice = field.getFieldPrice();
                String fieldPriceLight = field.getFieldPriceLight();
                System.out.println("fieldPrice:" + fieldPrice);
                //关灯时间
                System.out.println("fieldPriceLight:" + fieldPriceLight);
                //开灯时间

                DayOfWeek dayOfWeek = fieldBookingTime.getDayOfWeek();
                int hour = fieldBookingTime.getHour();
                int minute = fieldBookingTime.getMinute();
                //时间判断收费，只对ff进行赋值
                if (dayOfWeek.getValue() >= 1 && dayOfWeek.getValue() <= 5) {
                    //周一到周五
                    if ((hour == 16 && minute >= 20)
                            || (hour == 17)
                            || (hour == 18 && minute == 0)) {
                        msg = "该时间段免费使用，" + msg;
                        //免费时间
                    } else if ((hour == 8 && minute >= 30)
                            || (hour > 8 && hour < 11)
                            || (hour == 11 && minute <= 30)
                            || (hour == 14 && minute >= 30)
                            || (hour == 15)
                            || (hour == 16 && minute < 20)
                            || (hour > 18 && hour < 22)) {
                        //收费时间
                        if (light == 1) {
                            //判断是否开灯，调整收费
                            //关灯
                            try {
                                ff = Double.parseDouble(fieldPrice);
                            } catch (Exception e) {
                                System.out.println("不能将字符串转换为双精度数");
                            }
                        } else if (light == 2) {
                            //开灯
                            try {
                                ff = Double.parseDouble(fieldPriceLight);
                            } catch (Exception e) {
                                System.out.println("不能将字符串转换为双精度数");
                            }
                        } else {
                            flag = false;
                            msg = "错误开关灯代表值";
                            System.out.println("错误开关灯代表值");
                        }
                    } else {
                        //不可预约时间
                        flag = false;
                        msg = "周一到周五该时间段不可被租用";
                        System.out.println("周一到周五该时间段不可被租用");
                    }
                } else {
                    //周六日
                    if ((hour == 8 && minute >= 30)
                            || (hour > 8 && hour < 11)
                            || (hour == 11 && minute <= 30)
                            || (hour == 14 && minute >= 30)
                            || (hour > 14 && hour < 22)
                            || (hour == 22 && minute == 0)) {
                        //收费可预约时间
                        if (light == 1) {
                            //判断是否开灯，调整收费
                            try {
                                ff = Double.parseDouble(fieldPrice);
                            } catch (Exception e) {
                                System.out.println("不能将字符串转换为双精度数");
                            }
                        } else if (light == 2) {
                            try {
                                ff = Double.parseDouble(fieldPriceLight);
                            } catch (Exception e) {
                                System.out.println("不能将字符串转换为双精度数");
                            }
                        } else {
                            flag = false;
                            msg = "错误开关灯代表值";
                            System.out.println("错误开关灯代表值");
                        }
                    } else {
                        //不可预约时间
                        flag = false;
                        msg = "周六日该时间段不可被租用";
                        System.out.println("周六日该时间段不可被租用");
                    }
                }
                if (flag) {
                    String fieldname = field.getFieldName();

                    Rent rent = new Rent();
                    rent.setRentUser(userNum);
                    rent.setRentStart(fieldBookingTime);
                    LocalDateTime result = fieldBookingTime.plusHours(timeSize);
                    rent.setRentEnd(result);
                    rent.setRentPrice(ff * timeSize);
                    rent.setRentType("场地租借");
                    rent.setRentDtail("租借" + fieldname);
                    rent.setRentStatus("预约中");
                    rent.setRentField(id);
                    rentMapper.insert(rent);
                    System.out.println("租借表添加成功");

                    UpdateWrapper<Field> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("field_id", id); // 设置 WHERE 条件
                    updateWrapper.set("field_detail", "租用中");
                    fieldMapper.update(null, updateWrapper);
                }
            } else {
                msg = "场地已被租用，无法预约";
                System.out.println("rentList 不是空的，场地被租用,包含 " + rentList.size() + " 个元素");
            }
        }
        return new Result(flag ? StatusCode.SAVE_OK : StatusCode.SAVE_ERR, flag, msg);
    }

    @Override
    public Boolean unBooking(long fieldId) {
        boolean flag = false;
        QueryWrapper<Rent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rent_field", fieldId);
        List<Rent> rentList = rentService.list(queryWrapper);
        long RentID = 0;
        for (Rent rent : rentList) {
            if (rent.getRentStatus().equals("预约中")) {
                RentID = rent.getRentId();
                //获取租界表的id
                flag = true;
                break;
            }
        }

        if (flag) {
            System.out.println("查到租借数据");
            UpdateWrapper<Rent> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("rent_id", RentID); // 设置 WHERE 条件
            updateWrapper.set("rent_status", "已退订");
            rentMapper.update(null, updateWrapper);
            System.out.println("租借表rent已更改为‘已退订’");

            UpdateWrapper<Field> updateWrapper22 = new UpdateWrapper<>();
            updateWrapper22.eq("field_id", fieldId); // 设置 WHERE 条件
            updateWrapper22.set("field_detail", "闲置中");
            fieldMapper.update(null, updateWrapper22);
        } else {
            flag = false;
            System.out.println("该租借数据不存在");
        }
        return flag;
    }

    @Override
    public Result upDateBooking(long fieldId, int time, Long userNum) {
        boolean flag = false;
        String msg = "场地预约更新";
        QueryWrapper<Rent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rent_field", fieldId);
        List<Rent> rentList = rentService.list(queryWrapper);
        long RentID = 0;
        for (Rent rent : rentList) {
            if (rent.getRentStatus().equals("预约中")) {
                RentID = rent.getRentId();
                //获取租界表的id
                flag = true;
                break;
            }
        }
        if (flag) {
            System.out.println("查到租借数据");
            if (time > 0) {
                Rent rent = rentMapper.selectById(RentID);
                LocalDateTime fieldBookingTime = rent.getRentStart();
                System.out.println("RentStart:" + fieldBookingTime);
                //获取租借表开始时间
                LocalDateTime result = fieldBookingTime.plusHours(time);
                double ff = rent.getRentPrice();
                if (ff != 0.00) {
                    LocalDateTime oldTimeEnd = rent.getRentEnd();
                    //旧的结束时间，用于计算单价
                    Duration minutes = Duration.between(fieldBookingTime, oldTimeEnd);
                    long diffOldStartEnd = minutes.toMinutes();
                    int diffOldStartEnd1 = (int) diffOldStartEnd;
                    //得到分钟差
                    int hours = diffOldStartEnd1 / 60;
                    // 计算两者之间的小时差
                    double price2 = ff / hours;
                    //获取小时单价
                    ff = price2 * time;
                }
                UpdateWrapper<Rent> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("rent_id", RentID); // 设置 WHERE 条件
                updateWrapper.set("rent_end", result);
                updateWrapper.set("rent_price", ff);
                rentMapper.update(null, updateWrapper);
                //更新rent
            } else {
                flag = false;
                msg = "时间值错误，应大于0";
                System.out.println("时间值错误，应大于0");
            }
        } else {
            flag = false;
            msg = "该租借数据不存在";
            System.out.println("该租借数据不存在");
        }
        return new Result(flag ? StatusCode.UPDATE_OK : StatusCode.UPDATE_ERR, flag, msg);
    }

    @Override
    public Result stopBooking(long fieldId, Long userNum) {
        boolean flag = false;
        String msg = "查询成功";
        QueryWrapper<Rent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rent_field", fieldId);
        List<Rent> rentList = rentService.list(queryWrapper);

        long RentID = 0;
        for (Rent rent : rentList) {
            if (rent.getRentStatus().equals("预约中")) {
                RentID = rent.getRentId();
                //获取租界表的id
                flag = true;
                break;
            }
        }

        if (flag) {
            System.out.println("查到租借数据");
            Rent rent = rentMapper.selectById(RentID);
            LocalDateTime stopBookingTime = LocalDateTime.now();
            //获取现在时间
            LocalDateTime timeEnd = rent.getRentEnd();
            //获取结束时间
            Duration minutes = Duration.between(timeEnd, stopBookingTime);
            // 计算两者之间的时间差
            long diffMinutes = minutes.toMinutes();
            // 获取时间差值，以分钟为单位
            Bill bill = new Bill();
            double price = rent.getRentPrice();
            if (diffMinutes > 0) {
                //失约
                User user = userMapper.selectByPrimaryKey(userNum);
                int cred = user.getUserCred();
                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("user_num", userNum); // 设置 WHERE 条件
                updateWrapper.set("user_cred", cred - 10);
                userMapper.update(null, updateWrapper);
                // 更新用户的信用值

                LocalDateTime timeStart = rent.getRentStart();
                //获取开始时间
                Duration minutes2 = Duration.between(timeStart, timeEnd);
                long diffStartEnd = minutes2.toMinutes();
                int diffStartEnd1 = (int) diffStartEnd;
                //得到分钟差
                int hours = diffStartEnd1 / 60;
                // 计算两者之间的小时差
                double price2 = price / hours;
                //获取小时单价
                int eHour = (int) diffMinutes / 60;
                int eHour2 = (int) diffMinutes % 60 == 0 ? 0 : 1;
                eHour = eHour + eHour2;
                double ePrice = price2 + (price2 * eHour);

                bill.setBillPrice(ePrice);
                bill.setBillDetail("原金额+失约补交金额");
                msg = "您已失约，请补交额外的账单金额，扣信用分10分";
            } else {
                bill.setBillPrice(price);
                bill.setBillDetail("租用场地金额");
                //不失约
                msg = "您已按时归还，欢迎下次光临";
            }
            bill.setBillUser(userNum);
            bill.setBillType("场地租用");
            bill.setBillTime(LocalDateTime.now());
            billMapper.insert(bill);
            System.out.println("账单表添加成功");

            UpdateWrapper<Rent> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("rent_field", fieldId); // 设置 WHERE 条件
            updateWrapper.set("rent_status", "已完成");
            rentMapper.update(null, updateWrapper);
            System.out.println("租借表rent已更改为‘已完成’");
            flag = true;

            UpdateWrapper<Field> updateWrapper22 = new UpdateWrapper<>();
            updateWrapper22.eq("field_id", fieldId); // 设置 WHERE 条件
            updateWrapper22.set("field_detail", "闲置中");
            fieldMapper.update(null, updateWrapper22);
        } else {
            System.out.println("该租借数据不存在");
            msg = "该租借数据不存在";
        }
        Integer code = flag ? StatusCode.DELETE_OK : StatusCode.DELETE_ERR;
        return new Result(code, flag, msg);
    }
}




